import java.util.Arrays;

/*
 * @lc app=leetcode.cn id=322 lang=java
 *
 * [322] 零钱兑换
 */

// @lc code=start
class Solution {

    public int coinChange(int[] coins, int amount) {

        /* Solution 1
        if (amount == 0) return 0;

        int ans = Integer.MAX_VALUE;

        for (int coin : coins) {
            if (amount < coin) continue;
            int subProb = coinChange(coins, amount - coin);

            if(subProb == -1) continue;
            ans = Math.min(ans, subProb + 1);
        }

        return ans == Integer.MAX_VALUE? -1 : ans;
        */

        /* final solution 
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        
        dp[0] = 0;

        for (int i = 1; i <= amount; i++) {
            for (int coin : coins) {
                if (i-coin >= 0 && dp[i - coin] != amount + 1) {
                    dp[i] = Math.min(dp[i], 1 + dp[i - coin]);
                }
            }
        }

        if (dp[amount] == amount + 1) {
            dp[amount] = -1;
        }

        return dp[amount];
        */

        //reduo 1

        int[] dp = new int[amount + 1];
        dp[0] = 0;

        for (int i = 1; i < amount + 1; i++) {
            dp[i] = amount + 1;
        }

        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.length; j++) {
                if(i-coins[j] >= 0 && dp[i - coins[j]] != amount + 1) {
                    dp[i] = Math.min(dp[i - coins[j]] + 1, dp[i]);
                }
            }
        }

        if (dp[amount] == amount + 1) {
            dp[amount] = -1;
        }

        return dp[amount];

    }
}
// @lc code=end

